package com.cbd.util;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;

/**
 * @Author: CBD
 * @Date: 2024/11/22 10:18
 * @Description: 人脸识别工具类
 */
@Slf4j
@Component
public final class FaceUtil {
    //pFace client = new AipFace("Enter Your APP_ID", "Enter Your API_KEY", "Enter Your SECRET_KEY");
    public int faceUtils(AipFace client, String imagePath1, String imagePath2) {
        // 将图片文件转换为base64编码的字符串
        String image1 = encodeImageToBase64(String.valueOf(imagePath1));
        String image2 = encodeImageToBase64(String.valueOf(imagePath2));

        // image1/image2也可以为url或facetoken, 相应的imageType参数需要与之对应。
        MatchRequest req1 = new MatchRequest(image1, "BASE64");
        MatchRequest req2 = new MatchRequest(image2, "BASE64");
        ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
        requests.add(req1);
        requests.add(req2);

        JSONObject res = client.match(requests);
        log.info("人脸识别结果：{}", res.toString(2));

        // 从JSON对象中提取score
        if (res.has("result") && !res.isNull("result")) {
            JSONObject result = res.getJSONObject("result");
            if (result.has("score") && !result.isNull("score")) {
                return (int) result.getDouble("score");
            }
        }
        // 如果没有找到score，返回一个默认值或者抛出异常
        return -1; // 或者抛出一个异常
    }

    private String encodeImageToBase64(String imagePath) {
        try (FileInputStream imageInFile = new FileInputStream(imagePath)) {
            // 读取图片字节数据
            byte[] bytes = new byte[(int) new File(imagePath).length()];
            imageInFile.read(bytes);
            // 转换为base64编码的字符串
            return Base64.getEncoder().encodeToString(bytes);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
